/*
* Copyright (C) 2008-2009 J-P Nurmi jpnurmi@gmail.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* $Id$
*/

#include "textview.h"
#include "settings.h"
#include "application.h"
#include "nickhighlighter.h"
#include <QScrollBar>
#include <QTime>

TextView::TextView(QWidget* parent) : TextBrowser(parent)
{
    (void) new NickHighlighter(document());
}

TextView::~TextView()
{
}

void TextView::receiveMessage(const QString& format, const QStringList& params, bool highlight)
{
    QString message = format;
    foreach (const QString& param, params)
        message = message.arg(param);

    // workaround the link activation merge char format bug
    if (message.endsWith("</a>"))
        message += " ";

    const QString time = QTime::currentTime().toString();
    message = tr("[%1] %2").arg(time).arg(message);
    message = QString("<span style='color:%%color%%'>%1</span>").arg(message);

    appendMessage(message, highlight);
}

void TextView::appendMessage(QString message, bool highlight)
{
    Settings::ColorType color = Settings::Message;
    if (highlight)
        color = Settings::Highlight;
    else if (QRegExp("(<(span|p) [^>]*>)*\\[\\d+:\\d+:\\d+\\] ! .*").exactMatch(message))
        color = Settings::Event;
    else if (QRegExp("(<(span|p) [^>]*>)*\\[\\d+:\\d+:\\d+\\] \\? .*").exactMatch(message))
        color = Settings::Notice;
    else if (QRegExp("(<(span|p) [^>]*>)*\\[\\d+:\\d+:\\d+\\] \\[.*").exactMatch(message))
        color = Settings::Notice;
    else if (QRegExp("(<(span|p) [^>]*>)*\\[\\d+:\\d+:\\d+\\] \\* .*").exactMatch(message))
        color = Settings::Action;

    append(message.replace("%%color%%", Application::settings().colors.value(color)));
}
